package httpDownload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.net.Socket;

public class downloadThread extends Thread {
	HttpHead head;
	long begin;
	long offset;
	long index;
	int id;
	Socket socket;
	BufferedInputStream is;
	PrintWriter pw;
	File file;
	int SIZE = 1024;
	//exit file lenth,if not continued task , val is 0
	long exitFileLen = 0;

	public downloadThread(HttpHead head, int id) {
		
		
//		file = new File(Long.toString(System.currentTimeMillis()) + "+" + id);
		
		this(head,id,Long.toString(System.currentTimeMillis()) + "+" + id);
	}

	public downloadThread(HttpHead head, int id, String name) {

		this.head = head;
		this.id = id;
		file = new File(name + "+" + id);
		begin = head.getBegin();
		offset = head.getOffset();
		index = begin;
		if(file.exists() && file.isFile() && file.length()!= 0){
			//上次没有下载完成
			long exitFileLen = file.length();
			System.out.println(id + " thread continue download,file len " + exitFileLen);
			head.setBegin(exitFileLen + begin);
			head.setOffset(offset - exitFileLen );
//			head.setOffset(offset + exitFileLen - begin);
//			begin = head.getBegin();
//			offset = head.getOffset();
			index = head.getBegin();
//			offset -= head.getOffset();
		}
	}

	public void run() {
//		System.out.println(this.id + " " + head.toString());
		try {
			socket = new Socket(head.getHost(), head.getPort());
			is = new BufferedInputStream(socket.getInputStream());
			pw = new PrintWriter(socket.getOutputStream());
			pw.write(head.toString());
			pw.flush();
			String str;
			while ((str = readLine(is)) != null) {
//				System.out.println(id + "---" + str);
				continue; // 读掉头
			}
			byte[] buf = new byte[SIZE];
			//open oppend mode
			FileOutputStream fo = new FileOutputStream(file,true);
			// no necessery use  RandomAccessFile.
	//		RandomAccessFile fo = new RandomAccessFile(file, "rw");
//			FileWriter fo = new FileWriter(file, true);
//			fo.seek(fo.);
			while (index <= (begin + offset)) {
				int tlen = is.read(buf);
				if (tlen < 0){
					if(index < (begin + offset)){
//						System.out.println("bad net environment,please try again!");
						System.exit(-1);
					}
					break;
				}
				fo.write(buf, 0, tlen);
				index += tlen;
//				System.out.println(id + "+" + index);
			}
			is.close();
			pw.close();
//			fo.flush();
			
			fo.close();
			socket.close();
//			System.out.println("\n"+id + "  down" + "index " + index);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// this.notify();
		}
		pw.write(head.toString());
		pw.flush();
	}

	private String readLine(BufferedInputStream is) throws IOException {
		int buf;
		StringBuilder sb = new StringBuilder();
		while (true) {
			buf = is.read();
			// System.out.print((char)buf);
			if (buf == '\r') {
				// read '\n'
				is.read();
				break;
			}
			sb.append((char) buf);
		}

		return sb.length() != 0 ? sb.toString() : null;
	}

	public long getProgress() {
		synchronized (this) {
			return index - begin + 1;
		}
	}

	public String getFileName() {
		return this.file.getAbsolutePath();
	}

}
